package com.starbaba.apicount.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.apicount.model.StatApiCountModel;
import com.starbaba.apicount.service.StatApiCountService;
import com.starbaba.core.web.page.PageRequest;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;

public class StatApiCountServiceImpl implements StatApiCountService {
	BaseDao dao = new BaseDao(Constant.LOAN_STAT_DB_POOL);

	@Override
	public List<StatApiCountModel> getApiCountList(PageRequest request, PageResponse response, Map<String, Object> paramsMap)
			throws Exception {
		String activity = (String) paramsMap.get("activity_code");// 所属活动
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String tmodel = (String) paramsMap.get("tmodel");// 时间模式
		String smodel = (String) paramsMap.get("smodel");// 查看模式
		int start = request.getIDisplayStart();
		int length = request.getIDisplayLength();

		List<StatApiCountModel> list = new ArrayList<StatApiCountModel>();
		int count = 0;
		StringBuffer sql = new StringBuffer();
		sql.append("select * from stat_api_order where dateType=? ");

		if ("all".equals(activity)) {// 全部模式
			if ("1".equals(smodel)) {// 按比例查看
				if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
					sql.append(" and starttime>= '" + startTime + "' AND  lasttime<='" + endTime + "' ");
				}
				StringBuffer sqlAll = new StringBuffer();
				sqlAll.append("SELECT a.activity_code,a.activity_name, SUM(a.totalman) AS totalman,SUM(a.totalcount) totalcount,SUM(a.oneman) oneman ,");
				sqlAll.append("SUM(a.onecount) onecount,SUM(a.totalorder) totalorder,SUM(a.beginorder) beginorder,SUM(a.successorder) successorder,SUM(a.failorder) failorder,SUM(a.errororder) errororder ,a.dateType,a.ctime,a.lasttime ");
				sqlAll.append(" FROM(" + sql.toString() + ") a  GROUP BY a.ctime");

				count = dao.getInt("select count(z.activity_code) from (" + sqlAll.toString() + ") z", tmodel);

				if (sqlAll.length() > 0 && start >= 0 && length > 0) {
					sqlAll.append(" LIMIT " + start + ", " + length);
				}
				list = dao.list(sqlAll.toString(), StatApiCountModel.class, tmodel);

				String sqlCount = "SELECT a.activity_code,count(a.activity_code) as activity_count from ("
						+ sqlAll.toString() + ") a GROUP BY a.activity_code ";
				List<StatApiCountModel> listCount = dao.list(sqlCount, StatApiCountModel.class, tmodel);
				for (StatApiCountModel statApiCountModel : list) {
					for (StatApiCountModel countModle : listCount) {
						if (statApiCountModel.getActivity_code().equals(countModle.getActivity_code())) {
							long onecount = Long.parseLong(statApiCountModel.getActivity_count());
							long num = Long.parseLong(countModle.getActivity_count());
							String onecountNum = Long.toString(onecount * num);
							statApiCountModel.setActivity_count(onecountNum);
						}

					}
					statApiCountModel.setActivity_name("全部");
					statApiCountModel.setBeginorder(getPercent(statApiCountModel.getBeginorder(),
							statApiCountModel.getTotalorder()));
					statApiCountModel.setSuccessorder(getPercent(statApiCountModel.getSuccessorder(),
							statApiCountModel.getTotalorder()));
					statApiCountModel.setFailorder(getPercent(statApiCountModel.getFailorder(),
							statApiCountModel.getTotalorder()));
					statApiCountModel.setErrororder(getPercent(statApiCountModel.getErrororder(),
							statApiCountModel.getTotalorder()));
				}
			} else {// 按数值查看
				if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
					sql.append(" and starttime>= '" + startTime + "' AND  lasttime<='" + endTime + "' ");
				}
				StringBuffer sqlAll = new StringBuffer();
				sqlAll.append("SELECT a.activity_code,a.activity_name, SUM(a.totalman) AS totalman,SUM(a.totalcount) totalcount,SUM(a.oneman) oneman ,");
				sqlAll.append("SUM(a.onecount) onecount,SUM(a.totalorder) totalorder,SUM(a.beginorder) beginorder,SUM(a.successorder) successorder,SUM(a.failorder) failorder,SUM(a.errororder) errororder ,a.dateType,a.ctime,a.lasttime ");
				sqlAll.append(" FROM(" + sql.toString() + ") a GROUP BY a.ctime ");

				count = dao.getInt("select count(z.activity_code) from (" + sqlAll.toString() + ") z", tmodel);

				if (sqlAll.length() > 0 && start >= 0 && length > 0) {
					sqlAll.append(" LIMIT " + start + ", " + length);
				}
				list = dao.list(sqlAll.toString(), StatApiCountModel.class, tmodel);

				String sqlCount = "SELECT a.activity_code,count(a.activity_code) as activity_count from ("
						+ sqlAll.toString() + ") a GROUP BY a.activity_code ";
				List<StatApiCountModel> listCount = dao.list(sqlCount, StatApiCountModel.class, tmodel);
				for (StatApiCountModel statApiCountModel : list) {
					for (StatApiCountModel countModle : listCount) {
						if (statApiCountModel.getActivity_code().equals(countModle.getActivity_code())) {
							long onecount = Long.parseLong(statApiCountModel.getTotalman());
							long num = Long.parseLong(countModle.getActivity_count());
							String onecountNum = Long.toString(onecount * num);
							statApiCountModel.setActivity_count(onecountNum);
						}

					}
					statApiCountModel.setActivity_name("全部");
				}
		
			}

		} else { // 不是全部活动，即为查询单个活动
			sql.append("and activity_code=? ");
			if ("1".equals(smodel)) {// 按比例查看
				if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
					sql.append(" and starttime>= '" + startTime + "' AND  lasttime<='" + endTime + "' ");
				}
				count = dao.getInt("select count(z.activity_code) from (" + sql.toString() + ") z", tmodel, activity);

				if (sql.length() > 0 && start >= 0 && length > 0) {
					sql.append(" LIMIT " + start + ", " + length);
				}
				list = dao.list(sql.toString(), StatApiCountModel.class, tmodel, activity);
				for (StatApiCountModel statApiCountModel : list) {
					statApiCountModel.setBeginorder(getPercent(statApiCountModel.getBeginorder(),
							statApiCountModel.getTotalorder()));
					statApiCountModel.setSuccessorder(getPercent(statApiCountModel.getSuccessorder(),
							statApiCountModel.getTotalorder()));
					statApiCountModel.setFailorder(getPercent(statApiCountModel.getFailorder(),
							statApiCountModel.getTotalorder()));
					statApiCountModel.setErrororder(getPercent(statApiCountModel.getErrororder(),
							statApiCountModel.getTotalorder()));
				}

			} else {// 按数值查看
				if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
					sql.append(" and starttime>= '" + startTime + "' AND  lasttime<='" + endTime + "' ");
				}
				count = dao.getInt("select count(z.activity_code) from (" + sql.toString() + ") z", tmodel, activity);

				if (sql.length() > 0 && start >= 0 && length > 0) {
					sql.append(" LIMIT " + start + ", " + length);
				}
				list = dao.list(sql.toString(), StatApiCountModel.class, tmodel, activity);
			}
		}

		response.setITotalRecords(count);
		response.setITotalDisplayRecords(count);
		return list;
	}

	/**
	 * 转化称百分比
	 * 
	 * @param a
	 *            被除数
	 * @param b
	 *            除数
	 * @return
	 */
	public static String getPercent(String a, String b) {
		if (StringUtils.isEmpty(a) || StringUtils.isEmpty(b)) {
			return "0";
		}
		Long al = Long.parseLong(a);
		Long bl = Long.parseLong(b);

		return (float) Math.round((float) al / bl * 10000) / 100 + "%";
	}

	@Override
	public void topage(Map<String, Object> paramsMap) {
		String sql="select activity_code,activity_name from loan.loan_collab_activity where activety_type !=1";
		try {
			List<StatApiCountModel> list= dao.list(sql, StatApiCountModel.class);
			paramsMap.put("activityList", list);
		} catch (AppException e) {
			LogService.error(e);
		}
	}

	@Override
	public String exportDetailCVS(List<StatApiCountModel> list) {
		StringBuffer detail=new  StringBuffer();
		detail.append("时间,所属活动,总投递人数,总投递次数,一键投递人数,一键投递次数(活动数),订单总数,初审成功定单数,成功订单数,失败订单数,资格不符订单数\r\n");
		for (StatApiCountModel statApiCountModel : list) {
			detail.append(statApiCountModel.getCtime()).append(",");
			detail.append(statApiCountModel.getActivity_name()).append(",");
			detail.append(statApiCountModel.getTotalman()).append(",");
			detail.append(statApiCountModel.getTotalcount()).append(",");
			detail.append(statApiCountModel.getOneman()).append(",");
			detail.append(statApiCountModel.getOnecount()).append(",");
			detail.append(statApiCountModel.getTotalorder()).append(",");
			detail.append(statApiCountModel.getBeginorder()).append(",");
			detail.append(statApiCountModel.getSuccessorder()).append(",");
			detail.append(statApiCountModel.getFailorder()).append(",");
			detail.append(statApiCountModel.getErrororder()).append(",");
			detail.append("\r\n");
		}
		return detail.toString();
	}

}
